package com.jt.antiFakeSys.controller;

import cn.hutool.captcha.generator.RandomGenerator;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.ZipUtil;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.jt.antiFakeSys.Constants;
import com.jt.antiFakeSys.helper.AntiFakeCodeHelper;
import com.jt.antiFakeSys.model.AntiFakeCode;
import com.jt.antiFakeSys.service.AntiFakeCodeService;
import com.jt.base.utils.ExportUtil;
import com.jt.base.utils.PageUtil;
import com.jt.base.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;


/**
 * 防伪码(AntiFakeCode)表控制层
 *
 * @author longhp
 * @since 2019-03-02 13:24:37
 */
@RestController
@RequestMapping("antiFakeSys/antiFakeCode")
@Validated
@Slf4j
public class AntiFakeCodeController {
    @Resource
    private AntiFakeCodeService antiFakeCodeService;

    @Value("${file.temp.dir}")
    private String tempDir;

    @Resource
    private AntiFakeCodeHelper antiFakeCodeHelper;
    /**
     * 列表查询
     */
    @RequestMapping("/search")

    public R search(@Valid @Min(value = 0, message = "页码不能小于0") int page,
                    @Valid @Max(value = 1000, message = "请求数量最大不能超过1000") int limit,
                    @RequestParam(value = "id", required = false) Integer id,
                    @RequestParam(value = "name", required = false) String name,
                    @RequestParam(value = "code", required = false) String code,
                    @RequestParam(value = "status", required = false) Integer status
    ) {
        Example example = new Example(AntiFakeCode.class);
        Example.Criteria criteria = example.createCriteria();

        if (id != null) {
            criteria.andEqualTo("id", id);
        }
        if (StringUtils.isNotEmpty(name)) {
            criteria.andLike("name", "%" + name + "%");
        }
        if (status != null) {
            criteria.andEqualTo("status", status);
        }
        if (StringUtils.isNotEmpty(code)) {
            criteria.andLike("code", "%" + code + "%");
        }
        List<AntiFakeCode> list = antiFakeCodeService.selectListByExample(example, page, limit);
        return PageUtil.wrap(new PageInfo<>(list), R.ok());
    }

    /**
     * 修改和保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody AntiFakeCode antiFakeCode) {
        Integer id = antiFakeCode.getId();
        AntiFakeCode antiFakeCodeDb = antiFakeCodeService.selectByKey(id);
        if (antiFakeCodeDb != null) {
            antiFakeCodeService.updateNotNull(antiFakeCode);
        }
        return R.ok();
    }

    @RequestMapping("/generate")
    public R generate(@RequestParam("num") int num, @RequestParam("name") String name) {
        if (num > 0) {
            ThreadUtil.execAsync(
                    () -> {
                        RandomGenerator randomGenerator = new RandomGenerator(RandomUtil.BASE_NUMBER, 17);
                        for (int i = 0; i < num; i++) {
                            String code;
                            List<AntiFakeCode> antiFakeCodeList;
                            do {
                                // 判断码是否存在
                                code = randomGenerator.generate();
                                Example example = new Example(AntiFakeCode.class);
                                example.createCriteria().andEqualTo("code", code);
                                antiFakeCodeList = antiFakeCodeService.selectListByExample(example);
                            } while (antiFakeCodeList != null && antiFakeCodeList.size() > 0);
                            AntiFakeCode antiFakeCode = new AntiFakeCode();
                            antiFakeCode.setCode(code);
                            antiFakeCode.setName(name);
                            antiFakeCode.setStatus(Constants.FLAG_NO);
                            antiFakeCode.setCreateTime(new Date());
                            antiFakeCode.setSearchNum(0);
                            antiFakeCodeService.insert(antiFakeCode);
                        }
                    });
        }
        return R.ok();
    }


    /**
     * 状态修改
     */
    @RequestMapping("/updateStatus")
    public R updateStatus(@RequestParam("ids") String ids,
                          @RequestParam("status") int status) {
        Example example = new Example(AntiFakeCode.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andIn("id", Arrays.asList(ids.split(",")));
        List<AntiFakeCode> list = antiFakeCodeService.selectListByExample(example);
        if (list.size() > 0) {
          AntiFakeCode antiFakeCode = new AntiFakeCode();
                   antiFakeCode.setStatus(status);
                    antiFakeCodeService.updateNotNullByExample(antiFakeCode, example);
        }
        return R.ok();
    }


    /**
     * 次数清零
     */
    @RequestMapping("/clearNum")
    public R clearNum(@RequestParam("id") Integer id) {
        AntiFakeCode antiFakeCode = antiFakeCodeService.selectByKey(id);
        if (antiFakeCode!= null) {
            antiFakeCode.setSearchNum(0);
            antiFakeCode.setFirstSearchTime(null);
            antiFakeCodeService.update(antiFakeCode);
        }
        return R.ok();
    }

    /**
     * 上传日期修改
     */
    @RequestMapping("/dateUpdate")
    public R dateUpdate(@RequestParam("id") Integer id,@RequestParam("validateTime") Date validateTime) {
        AntiFakeCode antiFakeCode = antiFakeCodeService.selectByKey(id);
        if (antiFakeCode!= null) {
            antiFakeCode.setValidateTime(validateTime);
            antiFakeCodeService.update(antiFakeCode);
        }
        return R.ok();
    }

    /**
     * 信息
     */
    @RequestMapping("/get/{id}")
    public R get(@PathVariable("id") Integer id) {
        AntiFakeCode antiFakeCode = antiFakeCodeService.selectByKey(id);

        return R.ok().put("data", antiFakeCode);
    }


    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestParam("ids") String ids) {
        return R.ok();
    }


    @RequestMapping("/export")
    public void export(HttpServletResponse response, HttpServletRequest request) throws IOException {
        List<AntiFakeCode> list = antiFakeCodeService.selectAll();
        list.forEach(antiFakeCode ->{
            antiFakeCodeHelper.createQrCodeByCodeFile("http://wwww.21cn.com",
                    "诚信编码 : "+antiFakeCode.getCode(),
                    800,800,53,
                    tempDir+"/"+antiFakeCode.getCode()+".png");
        });
        response.setHeader("content-disposition", "attachment;filename=二维码.zip");
        File zipFile = ZipUtil.zip(tempDir);
        FileUtil.writeToStream(zipFile,response.getOutputStream());
    }


}